package com.ieng.ormosia.connect.service.impl;

import com.ieng.ormosia.connect.mapper.RoleMapper;
import com.ieng.ormosia.connect.mapper.RolePermissionMapper;
import com.ieng.ormosia.connect.model.Role;
import com.ieng.ormosia.connect.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private RolePermissionMapper rolePermissionMapper;

	@Override
	public List<Role> getRoleList() {
		return roleMapper.selectAll();
	}

	@Override
	public List<Role> getRoleHashQ(Role role) {
		return roleMapper.select(role);
	}

	@Override
	public List<Role> getRoleDelAll() {
		return roleMapper.selectDeletedList();
	}

	@Override
	public Role getRole(Long id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	@Transactional
	@Override
	public void addRole(Role role) {
		roleMapper.insert(role);
		if (role.getId() != null && role.getPermissionIds() != null) {
			rolePermissionMapper.insertPermissions(role.getId(), role.getPermissionIds());
		}
	}

	@Transactional
	@Override
	public void editRole(Role role) {
		if(role.getPermissionIds() != null && role.getPermissionIds().length > 0){
			rolePermissionMapper.delete(role.getId());
			rolePermissionMapper.insertPermissions(role.getId(), role.getPermissionIds());
		}
		roleMapper.update(role);
	}

	@Transactional
	@Override
	public void removeRole(Long id) {
		roleMapper.updateDeleted(id);
	}

	@Transactional
	@Override
	public void delRole(Long id) {
		rolePermissionMapper.delete(id);
		roleMapper.deleteByPrimaryKey(id);
	}
}
